package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.response.MealDetailInfo;
import com.pj.wisdomlogistics.mvp.contract.MealDetailContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.MealDetailPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.CustomAlertDialog;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.ButtonGrayUtils;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.PdfDownload;
import com.pj.wisdomlogistics.utils.ShowPop;
import com.pj.wisdomlogistics.utils.ToSign;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class MealDetialActivity extends MvpActivity<MealDetailPresenter> implements MealDetailContract.View,
        BaseActivity.RequestPermission,  ShowPop.listener {

    @BindView(R.id.tv_apply_state)
    TextView mTvApplyState;
    @BindView(R.id.tv_apply_basic_info)
    TextView mTvApplyBasicInfo;
    @BindView(R.id.tv_apply_detail_dept)
    TextView mTvApplyDetailDept;
    @BindView(R.id.tv_apply_detail_contacts)
    TextView mTvApplyDetailContacts;
    @BindView(R.id.tv_apply_detail_call)
    TextView mTvApplyDetailCall;
    @BindView(R.id.tv_apply_detail_phone)
    TextView mTvApplyDetailPhone;
    @BindView(R.id.tv_apply_detail_apply_date)
    TextView mTvApplyDetailApplyDate;
    @BindView(R.id.rel_basic_info)
    RelativeLayout mRelBasicInfo;
    @BindView(R.id.tv_apply_detail_meal_title)
    TextView mTvApplyDetailMealTitle;
    @BindView(R.id.tv_apply_detail_meal_type)
    TextView mTvApplyDetailMealType;
    @BindView(R.id.tv_apply_detail_meal_stand)
    TextView mTvApplyDetailMealStand;
    @BindView(R.id.tv_apply_detail_meal_reason)
    TextView mTvApplyDetailMealReason;
    @BindView(R.id.apply_detail_meal_date)
    TextView mApplyDetailMealDate;
    @BindView(R.id.iv_apply_leader_sign)
    ImageView mIvApplyLeaderSign;
    @BindView(R.id.ll_apply_leader_sign)
    LinearLayout mLlApplyLeaderSign;
    @BindView(R.id.tv_turn_sign)
    TextView mTvTurnSign;
    @BindView(R.id.tv_turn2_sign)
    TextView mTvTurn2Sign;
    @BindView(R.id.iv_apply_dept_stamp)
    ImageView mIvApplyDeptStamp;
    @BindView(R.id.ll_apply_dept_stamp)
    LinearLayout mLlApplyDeptStamp;
    @BindView(R.id.iv_apply_leader2_sign)
    ImageView mIvApplyLeader2Sign;
    @BindView(R.id.ll_apply_leader2_sign)
    LinearLayout mLlApplyLeader2Sign;
    @BindView(R.id.tv_apply_detail_manager_leader)
    TextView mTvApplyDetailManagerLeader;
    @BindView(R.id.tv_apply_detail_manager_charge_leader)
    TextView mTvApplyDetailManagerChargeLeader;
    @BindView(R.id.tv_turn_portion)
    TextView mTvTurnPortion;
    @BindView(R.id.tv_apply_detail_meal_count)
    TextView mTvApplyDetailMealCount;
    @BindView(R.id.bt_on)
    Button mBtOn;
    @BindView(R.id.bt_off)
    Button mBtOff;
    @BindView(R.id.tv_leader_name1)
    TextView mTvLeaderName1;
    @BindView(R.id.tv_leader_name2)
    TextView mTvLeaderName2;
    @BindView(R.id.tv_stamp_time)
    TextView mTvStampTime;
    @BindView(R.id.apply_detail_meal_remark)
    TextView mTvRemark;
    @BindView(R.id.tv_apply_detail_meal_place)
    TextView mTvPlace;

    private int mealId;
    private int mealTransactId;
    private String[] permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private String currentStampUrl = "";

    private int diningApplyID = -1;

    private String[] mMealStand;

    private boolean isSign1 = false;
    private boolean isSign2 = false;
    private int currentSign = -1;
    private boolean isCheck = false;
    private int currentSignState;

    @BindView(R.id.tv_undo)
    TextView mTvUndo;
    private CustomAlertDialog mCustomAlertDialog;

    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this, errorMsg, 1000);
    }

    @Override
    public void onSuccess(final MealDetailInfo mInfo) {
        dismissProgressDialog();

        diningApplyID = mInfo.getDiningApplyID();
        currentStampUrl = (String) mInfo.getCheck2Sign();

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .priority(Priority.HIGH);

        //已撤销的单子，或非首页、我的申请进来的单子，不展示撤销按钮
        if (mInfo.getCancel() == 1 || mealId == -1 || !mInfo.getUserID().equals(MyApplication.userID)) {
            mTvUndo.setVisibility(View.GONE);
        }else{
            mTvUndo.setVisibility(View.VISIBLE);
        }

        //申请领导签字
        if (mInfo.getCheck1() == 1) {
            mLlApplyLeaderSign.setVisibility(View.VISIBLE);
            Glide.with(this).load(mInfo.getCheck1Sign()).apply(options).into(mIvApplyLeaderSign);
        }

        //申请领导驳回
        if (mInfo.getCheck1() == 2) {
            mTvTurnSign.setVisibility(View.VISIBLE);
            mTvTurnSign.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck1Comments() + "   " + mInfo.getSignBackTime())));
        }

        //已盖章
        if (mInfo.getCheck2() == 1) {
            mLlApplyDeptStamp.setVisibility(View.VISIBLE);
            mTvStampTime.setText(mInfo.getSealTime());

            outer:
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                switch (MyApplication.user.getRoleId().get(i)) {
                    case Cons.RoleId.CHECK_MEAL:
                        ButtonGrayUtils.buttonGray(mBtOn, mBtOff, "同意", "驳回", mInfo.getState() <= 2);
                        break outer;
                    case Cons.RoleId.PORITION_MEAL:
                        ButtonGrayUtils.buttonGray(mBtOn, mBtOff, "分配", "驳回", mInfo.getState() <= 3);
                        break outer;
                }
            }
        }

        //区分管领导签字
        if (mInfo.getCheck3() == 1) {
            mLlApplyLeader2Sign.setVisibility(View.VISIBLE);
            Glide.with(this).load(mInfo.getCheck3Sign()).apply(options).into(mIvApplyLeader2Sign);
        }

        if (mInfo.getCheck3() == 2) {
            mTvTurn2Sign.setVisibility(View.VISIBLE);
            mTvTurn2Sign.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck3Comments() + "    " + mInfo.getLeaderSignBackTime())));
        }

        //已审核
        if (mInfo.getCheck4() == 1) {
            mTvApplyDetailManagerLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerLeader.setText(
                    "管理中心分管主任：已同意" + "    " +mInfo.getReviewName() + "    " + mInfo.getRevieweTime());
        } else if (mInfo.getCheck4() == 2) {
            mTvApplyDetailManagerLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerLeader.setText(String.format(
                    "管理中心分管主任" + mInfo.getCheck4Comments() + "    " + mInfo.getRevieweBackTime()));
        }

        //已分配(确认)
        if (mInfo.getCheck5() == 1) {
            mTvApplyDetailManagerChargeLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerChargeLeader.setText(
                   "管理中心分管领导：" + mInfo.getLeaderName() + " " + mInfo.getAllotTime()
            + "\n"+(!TextUtils.isEmpty(mInfo.getRoom()) ? "分配餐厅:" + mInfo.getRoom() : ""));
        }

        if (mInfo.getCheck5() == 2) {
            mTvTurnPortion.setVisibility(View.VISIBLE);
            mTvTurnPortion.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck5Comments() + "    " + mInfo.getAllotBackTime())));
        }

        mTvApplyDetailDept.setText(String.format(getResources().getString(R.string.apply_detail_dept, mInfo.getApplyDept())));
        mTvApplyDetailCall.setText(String.format(getResources().getString(R.string.apply_detail_call, mInfo.getOfficeTel())));
        mTvApplyDetailContacts.setText(String.format(getResources().getString(R.string.apply_detail_contacts, mInfo.getLinkman())));
        mTvApplyDetailPhone.setText(String.format(getResources().getString(R.string.apply_detail_phone, mInfo.getLinkmanTel())));
        mTvApplyDetailApplyDate.setText(String.format(getResources().getString(R.string.apply_detail_apply_date, mInfo.getCreateTime())));
        mTvApplyDetailMealType.setText(
                String.format(getResources().getString(R.string.tv_apply_detail_meal_type, mInfo.getDiningType() == 0 ? "桌餐" : mInfo.getDiningType() == 1 ? "自助餐" : "餐券")));
        if (mInfo.getDiningBenchmark() != 4) {
            mTvApplyDetailMealStand.setText(
                    String.format(getResources().getString(R.string.tv_apply_detail_meal_stand, mMealStand[mInfo.getDiningBenchmark()])));
        } else {
            mTvApplyDetailMealStand.setText("");
        }
        mTvApplyDetailMealReason.setText(String.format(getResources().getString(R.string.tv_apply_detail_meal_reason, mInfo.getDiningReason())));
        mTvApplyDetailMealCount.setText(String.format(getResources().getString(R.string.apply_detail_meal_count, mInfo.getPeopleCount())));
        mApplyDetailMealDate.setText(String.format(getResources().getString(R.string.apply_detail_meal_date, mInfo.getDiningTime())));
        mTvLeaderName1.setText(mInfo.getSignName() + "   " + mInfo.getSignTime());
        mTvLeaderName2.setText(mInfo.getSignName2() + "   " + mInfo.getLeaderSignTime());
        mTvRemark.setText("其他需要说明的情况："  + (TextUtils.isEmpty(mInfo.getRemark()) ? "无" : mInfo.getRemark()));
        if(mInfo.getPlace() == null){
            mTvPlace.setText("用餐地点：无");
        }else{
            mTvPlace.setText("用餐地点：" + (mInfo.getPlace().equals("1") ? "政府大楼" : mInfo.getPlace().equals("2") ? "双和园" : "无"));
        }



        ////////////////////////以上为基本信息，以下为我的待办//////////////////////////////////

        if ((mInfo.getState() == 0 || mInfo.getState() == 2) && mealTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if(MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.SIGN)
                        || MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.SIGN_QLD)){
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    currentSignState = mInfo.getState();

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //签字
                            ToSign.sign(MealDetialActivity.this);
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(MealDetialActivity.this, mInfo.getState() == 0 ? 7 : 8, mBtOff);
                        }
                    });
                }
            }

        }

        if (mInfo.getState() == 3 && mealTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.CHECK_MEAL)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);
                    mBtOn.setText("同意");
                    mBtOff.setText("驳回");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //审核
                            mPresenter.diningApplyReview(
                                    MyApplication.userID,
                                    diningApplyID,
                                    mInfo.getState() + "",
                                    ""
                            );
                            isCheck = true;
                            showProgressDialog();
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ShowPop.showTurnDown(MealDetialActivity.this, 9, mBtOff);
                        }
                    });
                }
            }
        }

        if (mInfo.getState() == 4 && mealTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.PORITION_MEAL)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);
                    mBtOn.setText("分配");
                    mBtOff.setText("驳回");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mInfo.getDiningType() == 0) {
                                startActivity(ChooseRoomActivity.class);
                            }else{
                                mPresenter.diningApplyFinish(
                                        MyApplication.userID,
                                        diningApplyID,
                                        "4",
                                        "",
                                        ""
                                );
                                showProgressDialog();
                            }
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ShowPop.showTurnDown(MealDetialActivity.this, 10, mBtOff);
                        }
                    });
                }
            }
        }
    }


    @Override
    public void onSignSuccess() {
        successToast(currentSign == 0 ? isSign1 ? "签字成功" : "驳回成功" : isSign2 ? "签字成功" : "驳回成功");
    }

    @Override
    public void onUndoSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "撤销成功", 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_APPLY));
        ActivityManagerUtil.create().finishActivity();
    }

    //审核
    @Override
    public void onReviewSuccess() {
        successToast(isCheck ? "审核成功" : "驳回成功");
    }

    @Override
    public void onFinishSuccess() {
        successToast("分配成功");
    }

    public void successToast(String toast) {
        dismissProgressDialog();
        CustomToast.showToast(this, toast, 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_TRANSACT));
        mPresenter.findDiningApplyDetail(mealId != -1 ? mealId : mealTransactId);
        mBtOn.setVisibility(View.GONE);
        mBtOff.setVisibility(View.GONE);
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));

        mealId = getIntent().getIntExtra(Cons.MealInfo.MEAL_ID, -1);
        mealTransactId = getIntent().getIntExtra(Cons.MealInfo.MEAL_RANSACT_ID, -1);

        setRequestPermissionListener(this);

        mPresenter.findDiningApplyDetail(mealId != -1 ? mealId : mealTransactId);
        showProgressDialog();

        mMealStand = getResources().getStringArray(R.array.meal_standard);

        ShowPop.setListner(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_meal_detial;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Cons.MealInfo.ROOM) {
            String room = (String) eventCenter.getData();
            //分配
            mPresenter.diningApplyFinish(
                    MyApplication.userID,
                    diningApplyID,
                    "4",
                    "",
                    room
            );
            showProgressDialog();
        }
    }


    @OnClick({R.id.iv_back, R.id.iv_apply_dept_stamp , R.id.tv_undo})
    public void onViewClicked(View mView) {
        switch (mView.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.iv_apply_dept_stamp:
                if (!checkPermissions(permission)) {
                    requestSystemPermissions(permission, 101);
                } else {
                    PdfDownload.pdfDownload(this, currentStampUrl);
                }
                break;
            case R.id.tv_undo:
                mCustomAlertDialog = new CustomAlertDialog.Builder(this)
                        .setMessage("确认撤销该申请单吗？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.cancelDiningApply(mealId != -1 ? mealId : mealTransactId);
                                showProgressDialog();
                                mCustomAlertDialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mCustomAlertDialog.dismiss();
                            }
                        }).create();
                mCustomAlertDialog.show();
                break;
        }

    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 101) {
            if (!checkPermissions(permission)) {
                CustomToast.showToast(this, "您拒绝了相关权限的请求", 1000);
            } else {
                PdfDownload.pdfDownload(this, currentStampUrl);
            }
        }
    }


    @Override
    public void showTurnDown(int state, String text, int rating) {
        switch (state) {
            case 7:
                mPresenter.diningApplySign(
                        MyApplication.userID,
                        diningApplyID,
                        null,
                        state,
                        text
                );
                isSign1 = false;
                currentSign = 0;
                break;
            case 8:
                mPresenter.diningApplySign2(
                        MyApplication.userID,
                        diningApplyID,
                        null,
                        state,
                        text
                );
                isSign2 = false;
                currentSign = 1;
                break;
            case 9:
                mPresenter.diningApplyReview(
                        MyApplication.userID,
                        diningApplyID,
                        state + "",
                        text
                );
                isCheck = false;
                break;
            case 10:
                mPresenter.diningApplyFinish(
                        MyApplication.userID,
                        diningApplyID,
                        state + "",
                        text,
                        ""
                );
                break;
        }
        showProgressDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1){
            String path = data.getStringExtra("path");
            if(TextUtils.isEmpty(path)) return;
            File mFile = new File(path);

            toSign(mFile);
            showProgressDialog();
        }
    }

    private void toSign(File mFile){
        //上传签名
        switch (currentSignState) {
            case 0:
                mPresenter.diningApplySign(
                        MyApplication.userID,
                        diningApplyID,
                        mFile,
                        1,
                        ""
                );
                isSign1 = true;
                currentSign = 0;
                break;
            case 2:
                mPresenter.diningApplySign2(
                        MyApplication.userID,
                        diningApplyID,
                        mFile,
                        3,
                        ""
                );
                isSign2 = true;
                currentSign = 1;
                break;
        }
    }
}
